<template>
  <div class="toast-container" v-if="toasts.length > 0">
    <div 
      v-for="toast in toasts" 
      :key="toast.id"
      :class="['toast', `toast-${toast.type}`]"
      @click="removeToast(toast.id)"
    >
      <span class="toast-message">{{ toast.message }}</span>
      <button class="toast-close" @click.stop="removeToast(toast.id)">×</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const toasts = ref([])
let toastId = 0

const addToast = (message, type = 'info', duration = 3000) => {
  const id = ++toastId
  toasts.value.push({ id, message, type })
  
  // 自动移除
  setTimeout(() => {
    removeToast(id)
  }, duration)
}

const removeToast = (id) => {
  const index = toasts.value.findIndex(t => t.id === id)
  if (index > -1) {
    toasts.value.splice(index, 1)
  }
}

const handleShowNotification = (event) => {
  const { message, type = 'info' } = event.detail || {}
  if (message) {
    addToast(message, type)
  }
}

onMounted(() => {
  window.addEventListener('show-notification', handleShowNotification)
})

onUnmounted(() => {
  window.removeEventListener('show-notification', handleShowNotification)
})

// 暴露全局方法
window.showToast = addToast
</script>

<style scoped>
.toast-container {
  position: fixed;
  top: 80px;
  right: 20px;
  z-index: 9999;
  display: flex;
  flex-direction: column;
  gap: 8px;
  pointer-events: none;
}

.toast {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-radius: 8px;
  color: var(--text-inverse);
  font-size: 14px;
  font-weight: 500;
  box-shadow: var(--shadow-card);
  backdrop-filter: blur(10px);
  border: 1px solid var(--border);
  min-width: 200px;
  max-width: 300px;
  pointer-events: auto;
  animation: slideIn 0.3s ease-out;
}

.toast-success {
  background: var(--accent-success);
  border-color: var(--accent-success);
}

.toast-error {
  background: var(--accent-danger);
  border-color: var(--accent-danger);
}

.toast-info {
  background: var(--accent-secondary);
  border-color: var(--accent-secondary);
}

.toast-warning {
  background: var(--accent-warning);
  border-color: var(--accent-warning);
}

.toast-message {
  flex: 1;
  margin-right: 8px;
}

.toast-close {
  background: none;
  border: none;
  color: var(--text-inverse);
  font-size: 18px;
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.7;
  transition: opacity 0.2s;
}

.toast-close:hover {
  opacity: 1;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@media (max-width: 768px) {
  .toast-container {
    top: 60px;
    right: 10px;
    left: 10px;
  }
  
  .toast {
    max-width: none;
    width: 100%;
  }
}
</style>